package com.jiukuaidao.zhulin.module.commodity;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jiukuaidao.library.Config;
import com.jiukuaidao.library.base.BaseFragment;
import com.jiukuaidao.library.base.BaseHolder;
import com.jiukuaidao.library.base.BaseXrecyclerViewAdapter;
import com.jiukuaidao.library.util.ImageGlideUtils;
import com.jiukuaidao.library.util.LogUtil;
import com.jiukuaidao.library.widget.recyclerview.XRecyclerView;
import com.jiukuaidao.zhulin.R;
import com.jiukuaidao.zhulin.data.TaskProvider;
import com.jiukuaidao.zhulin.entity.ApiGeoCoderInfo;
import com.jiukuaidao.zhulin.entity.ApiHistoryAddressInfo;
import com.jiukuaidao.zhulin.entity.ApiSortCatList;
import com.jiukuaidao.zhulin.entity.ApiSortPros;
import com.jiukuaidao.zhulin.entity.EventShoppingCartInfo;
import com.jiukuaidao.zhulin.module.CommContract;
import com.jiukuaidao.zhulin.module.CommPresenter;
import com.jiukuaidao.zhulin.module.commodity.contract.SortProContract;
import com.jiukuaidao.zhulin.module.commodity.presenter.SortProPresenter;
import com.jiukuaidao.zhulin.module.home.contract.HomeContract;
import com.jiukuaidao.zhulin.util.AddressInfoUtil;
import com.jiukuaidao.zhulin.util.ShopInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Author : H_Joker
 * Date : 2016/6/6
 * Description :
 */
public class SortProFragment extends BaseFragment<SortProContract.Presenter> implements SortProContract.View, XRecyclerView.OnRefreshListener, CommContract.ShoppingCartLocalView {

    @BindView(R.id.xrl_products)
    XRecyclerView xrlProducts;

    BaseXrecyclerViewAdapter mProListAdapter;

    private CommPresenter mCommPresenter;
    /**
     * 当前加减购物车的商品货号
     */
    private String mCurProNumber;

    /**
     * 当前加减购物车的商品价格
     */
    private String mCurProPrice;

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        initRecyclerView();
        onRefresh();
    }

    private void initRecyclerView() {
        GridLayoutManager layoutManager = new GridLayoutManager(Config.mContext, 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mProListAdapter = new BaseXrecyclerViewAdapter<ApiSortPros.ApiSortProItem>(Config.mContext, R.layout.item_home_goodslist, mPresenter.getPros(), xrlProducts) {
            @Override
            public void updateUI(BaseHolder holder, int position, ApiSortPros.ApiSortProItem data) {
                ImageGlideUtils.GlideImages(SortProFragment.this, data.uri, (ImageView) holder.getView(R.id.img_product), R.mipmap.ic_launcher);
                ((TextView) holder.getView(R.id.tv_proName)).setText(data.name);
                ((TextView) holder.getView(R.id.price_product)).setText("￥" + data.retailPrice);

                // 购物车中数量
                String proNumber = data.number;
                List<EventShoppingCartInfo> shoppingCart = mPresenter.getShoppingCart();
                int count = 0;
                if (shoppingCart != null) {
                    for (EventShoppingCartInfo item : shoppingCart) {
                        if (proNumber.equals(item.getGoodsGN())) {// 如果数据库中有此商品
                            count = item.getCount();
                            break;
                        }
                    }
                }
                if (count <= 0) {// 购物车中没有此商品
                    holder.getView(R.id.add_good_image).setVisibility(View.VISIBLE);
                    holder.getView(R.id.reduce_good_image).setVisibility(View.GONE);
                    holder.getView(R.id.current_good_count).setVisibility(View.GONE);
                } else {// 购物车中有此商品
                    holder.getView(R.id.add_good_image).setVisibility(View.VISIBLE);
                    holder.getView(R.id.reduce_good_image).setVisibility(View.VISIBLE);
                    holder.getView(R.id.current_good_count).setVisibility(View.VISIBLE);
                    ((TextView) holder.getView(R.id.current_good_count)).setText("" + count);

                }
            }

            @Override
            protected void setTouchListener(final BaseHolder holder, final int position) {
                super.setTouchListener(holder, position);
                // 购物车增加商品
                holder.getView(R.id.add_good_image).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCurProNumber = mPresenter.getPros().get(position).number;
                        mCurProPrice = mPresenter.getPros().get(position).retailPrice;
                        mCommPresenter.addShoppingCartLocal();
                    }
                });

                // 购物车减少商品
                holder.getView(R.id.reduce_good_image).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mCurProNumber = mPresenter.getPros().get(position).number;
                        mCurProPrice = mPresenter.getPros().get(position).retailPrice;
                        mCommPresenter.reduceShoppingCartLocal();
                    }
                });

            }

            @Override
            protected void onItemClick(BaseHolder holder, int position) {
                super.onItemClick(holder, position);
                // 跳转至商品详情
                String proId = mPresenter.getPros().get(position).id;
                String deliveryLimit = String.valueOf(ShopInfoUtil.getDeliveryLimit());
                String deliveryFull = ShopInfoUtil.getFullShipmentFree();

                Bundle bundle = new Bundle();
                bundle.putString("goodsId", proId);
                bundle.putString("startPrice", deliveryLimit);
                bundle.putString("fullShipmentFree",deliveryFull);
                intentJump(GoodsDetailActivity.class, bundle);

            }
        };

        xrlProducts.setLayoutManager(layoutManager);
        xrlProducts.setAdapter(mProListAdapter);
        xrlProducts.setOnRefreshListener(this);
    }

    @Override
    protected void bindMVP() {
        new SortProPresenter(TaskProvider.provideSortProRepository(Config.mContext), this);
        mCommPresenter = new CommPresenter(TaskProvider.provideTasksRepository(getActivity()), this);
        mCommPresenter.getShoppingCartDataLocal();
    }

    @Override
    protected void handleBundle(Bundle bundle) {
        if (bundle != null) {
            ApiSortCatList.ApiSortCateListItem cateInfo = (ApiSortCatList.ApiSortCateListItem) bundle.getSerializable("cateInfo");
            mPresenter.setCateInfo(cateInfo);
        }
    }

    @Override
    protected View getTargetView() {
        return null;
    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {

    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_sortpro;
    }

    @Override
    public void onRefresh() {
        String cateIds = mPresenter.getCateInfo().id;
//        cateIds = "1";
        String cityCode = AddressInfoUtil.getAddressInfo().cityCode;
        String latitude = AddressInfoUtil.getAddressInfo().latitude;
        String longitude = AddressInfoUtil.getAddressInfo().longitude;
        mPresenter.loadProList(SortProContract.REFRESH, cateIds, 1, latitude, longitude, cityCode, null, null, null);
    }

    @Override
    public void onLoadMore() {
        String cateIds = mPresenter.getCateInfo().id;
//        cateIds = "1";
        String cityCode = AddressInfoUtil.getAddressInfo().cityCode;
        String latitude = AddressInfoUtil.getAddressInfo().latitude;
        String longitude = AddressInfoUtil.getAddressInfo().longitude;
        mPresenter.loadProList(SortProContract.LOADMORE, cateIds, mPresenter.getCurrentPageIndex() + 1, latitude, longitude, cityCode, null, null, null);
    }

    @Override
    public void refreshProsUi() {
        mProListAdapter.setData(mPresenter.getPros());
        mProListAdapter.notifyDataSetChanged();
    }

    /**
     * 购物车改变
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventShopingCart(List<EventShoppingCartInfo> datas) {
        LogUtil.log("分类收到信息");
        mPresenter.setShoppingCart(datas);
        mProListAdapter.notifyDataSetChanged();
    }

    /**
     * 定位当前位置 接收的地址
     *
     * @param apiGeoCoderInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventLocationResult(ApiGeoCoderInfo apiGeoCoderInfo) {
        onRefresh();
    }

    /**
     * 地址切换 点击用户收货地址 接收的地址
     *
     * @param data
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventUserAddress(ApiHistoryAddressInfo.AddressInfo data) {
        onRefresh();
    }

    /**
     * 地址切换 点击搜索地址 接收的地址
     *
     * @param map
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventPlace(Map<String, String> map) {
        onRefresh();
    }

    @Override
    public void loadComplete(int act, boolean isOver, boolean isEmpty) {
        LogUtil.log("act：" + act + " isOver:" + isOver + " isEmpty" + isEmpty);

        if (act == HomeContract.REFRESH) {
            xrlProducts.refreshComplete();
        } else {
            xrlProducts.loadMoreComplete();
        }
        if (isOver) {
            xrlProducts.loadNoMore();
        }
        if (isEmpty) {
//            mNoProLayout.setVisibility(View.VISIBLE);
        } else {
//            mNoProLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public String getGoodsNumber() {
        return mCurProNumber;
    }

    @Override
    public String getGoodsCurPrice() {
        return mCurProPrice;
    }
}
